﻿using System;
using System.IO;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MyWebPagesStarterKit.Controls;
using MyWebPagesStarterKit;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public partial class SectionControls_DownloadManager : SectionControlBaseClass
{
    private DownloadManager _section;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            EnsureID();
        }
    }

    protected void Actions(object sender, CommandEventArgs e)
    {
        ViewState["Action"] = e.CommandName;
    }

    protected void Cansel(object sender, EventArgs e)
    {
        ViewState["Action"] = null;

    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        updateViews();
    }



    protected void Folder_RowCommand(object source, GridViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "editfolder":
                ViewState["Action"] = "Edit";
                ViewState["Edit"] = folderList.DataKeys[int.Parse(e.CommandArgument.ToString())].Value;
                divFileList.Visible = true;
                break;
            case "deletefoler":
                string currentfolder = Convert.ToString(folderList.DataKeys[int.Parse(e.CommandArgument.ToString())].Value);
                _section.Remove(currentfolder);
                _section.SaveData();
                break;
        }
    }


    protected void File_RowCommand(object source, GridViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "editfile":
                ViewState["Action"] = "EditFile";
                ViewState["Edit"] = ViewState["Edit"];
                ViewState["EditFile"] = dlfileList.DataKeys[int.Parse(e.CommandArgument.ToString())].Value;
                divFileList.Visible = true;
                break;

            case "deletefile":
                string currentfile = Convert.ToString(dlfileList.DataKeys[int.Parse(e.CommandArgument.ToString())].Value);
                _section.Remove(currentfile);
                _section.SaveData();
                break;
        }
    }



    private void updateViews()
    {
        string Action = null;

        if (ViewState["Action"] != null)
            Action = Convert.ToString(ViewState["Action"]);

        if (ViewMode == ViewMode.Edit)
        {
            switch (Action)
            {
                case null:
                    multiview.SetActiveView(folderView);
                    List<MyWebPagesStarterKit.DownloadManager.VersionFile> list = _section.AdminFolders;
                    folderList.DataSource = list;
                    folderList.DataBind();
                    break;

                case "Add": //Add folder
                    multiview.SetActiveView(editView);
                    txtTitle.Text = string.Empty;
                    txtComment.Text = string.Empty;
                    txtFilename.Text = string.Empty;
                    txtVersion.Text = string.Empty;
                    btnSave.Visible = true;
                    btnSaveFile.Visible = false;
                    break;

                case "Edit": //Edit folder
                    multiview.SetActiveView(editView);
                    MyWebPagesStarterKit.DownloadManager.VersionFile folder = _section.GetFolder(Convert.ToString(ViewState["Edit"]));
                    txtTitle.Text = folder.Title;
                    txtComment.Text = folder.Comment;
                    txtFilename.Text = folder.FileName;
                    txtVersion.Text = folder.Version;
                    chkActive.Checked = folder.Active;
                    //Load files
                    List<MyWebPagesStarterKit.DownloadManager.VersionFile> filesList = _section.AdminFilesInFolder(Convert.ToString(ViewState["Edit"]));
                    dlfileList.DataSource = filesList;
                    dlfileList.DataBind();
                    btnSave.Visible = true;
                    btnSaveFile.Visible = false;

                    break;

                case "AddFile": //Add file
                    multiview.SetActiveView(editView);
                    txtTitle.Text = string.Empty;
                    txtComment.Text = string.Empty;
                    txtFilename.Text = string.Empty;
                    txtVersion.Text = string.Empty;
                    chkActive.Checked = false;
                    btnSave.Visible = false;
                    btnSaveFile.Visible = true;

                    break;

                case "EditFile": // Edit file
                    multiview.SetActiveView(editView);
                    MyWebPagesStarterKit.DownloadManager.VersionFile file = _section.GetFolder(Convert.ToString(ViewState["EditFile"]));
                    txtTitle.Text = file.Title;
                    txtComment.Text = file.Comment;
                    txtFilename.Text = file.FileName;
                    txtVersion.Text = file.Version;
                    chkActive.Checked = file.Active;
                    btnSave.Visible = false;
                    btnSaveFile.Visible = true;
                    break;
            }
        }
        else
        {
            if (Request["Folder"] == null)
            {
                multiview.SetActiveView(readonlyView);
                List<MyWebPagesStarterKit.DownloadManager.VersionFile> list = _section.PublicFolders;
                dlList.DataSource = list;
                dlList.DataBind();
            }

            if (Request["Folder"] != null)
            {
                multiview.SetActiveView(fileView);

                List<MyWebPagesStarterKit.DownloadManager.VersionFile> list = _section.PublicFilesInFolder(Request["Folder"]);
                dlFileInFolder.DataSource = list;
                dlFileInFolder.DataBind();
            }
        }
    }




    protected void AddFolder(object sender, EventArgs e)
    {

        if (ViewState["Edit"] == null)
        {

            string id = Guid.NewGuid().ToString();
            string file = string.Empty;
            if (fileupload1.HasFile)
                file = FileName(fileupload1, "DownloadManager/Files", txtVersion.Text);

            _section.Add(id, txtTitle.Text, txtComment.Text, file, txtVersion.Text, chkActive.Checked, true, id);

        }
        else
        {
            MyWebPagesStarterKit.DownloadManager.VersionFile vfile = _section.GetFolder(Convert.ToString(ViewState["Edit"]));

            vfile.Title = txtTitle.Text;
            vfile.Comment = txtComment.Text;

            string file = string.Empty;
            if (fileupload1.HasFile)
                file = FileName(fileupload1, "DownloadManager/Files", txtVersion.Text);
            else
                file = txtFilename.Text;

            vfile.Version = txtVersion.Text;
            vfile.Active = chkActive.Checked;
            vfile.IsFolder = true;
            vfile.DateChanged = DateTime.Now;

            _section.SaveData();

        }
    }



    //Add file
    protected void AddFile(object sender, EventArgs e)
    {
        if (ViewState["EditFile"] == null)
        {
            string id = Guid.NewGuid().ToString();
            string parent = Convert.ToString(ViewState["Edit"]);


            string file = string.Empty;
            if (fileupload1.HasFile)
                file = FileName(fileupload1, "DownloadManager/Files", txtVersion.Text);

            _section.Add(id, txtTitle.Text, txtComment.Text, file, txtVersion.Text, chkActive.Checked, false, parent);
        }
        else
        {
            MyWebPagesStarterKit.DownloadManager.VersionFile vfile = _section.GetFolder(Convert.ToString(ViewState["EditFile"]));

            vfile.Title = txtTitle.Text;
            vfile.Comment = txtComment.Text;

            string file = string.Empty;
            if (fileupload1.HasFile)
                file = FileName(fileupload1, "DownloadManager/Files", txtVersion.Text);
            else
                file = txtFilename.Text;

            vfile.Version = txtVersion.Text;
            vfile.Active = chkActive.Checked;
            vfile.IsFolder = false;
            vfile.DateChanged = DateTime.Now;

            _section.SaveData();
        }
    }



    #region files


    public string FileName(FileUpload fileupload, string sectionpath, string version)
    {
        string strFilename = string.Empty;
        if (fileupload.HasFile)
        {
            HttpPostedFile myFile = fileupload.PostedFile;
            int nFileLen = myFile.ContentLength;
            if (nFileLen > 0)
            {
                byte[] myData = new byte[nFileLen];
                myFile.InputStream.Read(myData, 0, nFileLen);
                strFilename = version + "-" + Path.GetFileName(myFile.FileName).ToLower();

                string _path = Server.MapPath("/App_Data/" + sectionpath + "/" + strFilename);

                if (!Directory.Exists(Path.GetDirectoryName(_path)))
                    Directory.CreateDirectory(Path.GetDirectoryName(_path));

                WriteToFile(strFilename, _path, ref myData);
            }
        }
        return strFilename;
    }


    private void WriteToFile(string strFilename, string strPath, ref byte[] Buffer)
    {
        FileStream newFile = new FileStream(strPath, FileMode.Create);
        newFile.Write(Buffer, 0, Buffer.Length);
        newFile.Close();
    }



    private string makeFilenameUnique(string path)
    {
        if (File.Exists(path))
        {
            int i = 1;
            while (true)
            {
                string temppath = path.Insert(path.LastIndexOf('.'), string.Format("[{0}]", i++));
                if (!File.Exists(temppath))
                    return temppath;
            }
        }
        else
        {
            return path;
        }
    }


    #endregion


    public string GetFolderLink(string id)
    {
        return string.Format("/{0}?Action=Folder&Folder={1}", WebPage.Current.VirtualPath.Replace("~/",""), id);
    }

    public string GetFileLink(string id)
    {
        return string.Format("/{0}?Action=File&FileID={1}", WebPage.Current.VirtualPath.Replace("~/", ""), id);
    }

    public string GetLink(string id, string title)
    {
        return string.Format("<a href=\"/Download.ashx?file={0}&section={1}\" title=\"Click to download\">{2}</a>", id, _section.SectionId, title);
    }

    protected string GetBackLink()
    {
        return WebPage.Current.VirtualPath.Replace("~/", "");
    }

    public string GetFileCount(string id)
    {
        string count = "0";
        int c = _section.PublicFilesInFolder(id).Count;

        if (c > 0)
            count = Convert.ToString(c);

        return count;
    }

    public override ISection Section
    {
        set
        {
            if (value is DownloadManager)
                _section = (DownloadManager)value;
            else
                throw new ArgumentException("Section must be of type DownloadManager");
        }
        get { return _section; }
    }

    public override bool HasAdminView
    {
        get { return true; }
    }

    public override string InfoUrl
    {
        get
        {
            string lang = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
            if (File.Exists(HttpContext.Current.Server.MapPath(string.Format("Documentation/" + lang + "/quick_guide.html"))))
            {
                return "Documentation/" + lang + "/quick_guide.html#DownloadManager";
            }
            else
            { return "Documentation/en/quick_guide.html#html-content"; }
        }
    }
}
